
#include <iostream>
#include <cstdio>
#include "Thread.h"
#include "BlockQueue.h"
#include <unistd.h>

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void Producer(zmh::block_queue<std::string> &bq, std::string name) // 生产者
{
    while (true)
    {
        char buffer[1024] = {0};
        snprintf(buffer, sizeof(buffer) - 1, "%s,释放了一条漂流瓶:好想谈恋爱,不知花落谁家", name.c_str());
        bq.producer(buffer);

        // 测试信息
        pthread_mutex_lock(&gmutex);
        std::cout << buffer << std::endl;
        pthread_mutex_unlock(&gmutex);
        sleep(1);
    }
}

void Consumer(zmh::block_queue<std::string> &bq, std::string name) // 消费者
{
    while (true)
    {
        std::string buffer = bq.consumer();

        // 测试信息
        pthread_mutex_lock(&gmutex);
        printf("%s,捡到了一条漂流瓶,内容:%s\n", name.c_str(), buffer.c_str());
        pthread_mutex_unlock(&gmutex);
        sleep(1);
    }
}

int main()
{
    zmh::block_queue<std::string> bq;

    zmh::Thread p1(Producer, std::ref(bq), "无感");
    zmh::Thread p2(Producer, std::ref(bq), "常梦圆");
    zmh::Thread p3(Producer, std::ref(bq), "李阳");

    zmh::Thread c1(Consumer, std::ref(bq), "刘爽");
    zmh::Thread c2(Consumer, std::ref(bq), "庄梦涵");
    zmh::Thread c3(Consumer, std::ref(bq), "刘亦菲");
    zmh::Thread c4(Consumer, std::ref(bq), "孟子义");
    zmh::Thread c5(Consumer, std::ref(bq), "董高洁");

    p1.join();
    p2.join();
    p3.join();

    c1.join();
    c2.join();
    c3.join();
    c4.join();
    c5.join();

    return 0;
}